import {getStorageSync} from "../utils/Storage";
const requestRecord = {}; //请求记录栈  防重复
const requestExpiredErr = {}; //请求登录过期错误栈
const requestNetworkErr = {}; //请求网络错误栈
/*
* 获取请求名
* */
function _getRequestName (params) {
    let str = "";
    let {url, data} = params;
    if (Object.keys(data).length > 0) {
        for (let i in data) {
            str += (i + "=" + data[i] + "&")
        }
        str = str.substr(0, str.length - 1);
    }
    if (url.indexOf("?") === -1) {
        return str ? (url + "?" + str) : url
    } else {
        return str ? (url + "&" + str) : url
    }
}



const Request = {
    /*
    * 请求
    * */
    request: function (params) {
        return new Promise(function (resolve, reject) {
            let {url, header = {}} = params,
                token = getStorageSync("token");
            if (!url) {reject(new Error("request.url is not found"))} //url 不存在
            let requestName = _getRequestName(params); //设置请求唯名称
            if (requestRecord[requestName]) {return false}; //重复请求控制
            token ? header.Authorization = token.token : null;
            params.header ? params.header = Object.assign(params.header, header) : null;
            Object.keys(header).length > 0 ? params.header = header : null;
            requestRecord[requestName] = wx.request({
                ...params,
                success: function (res) {
                    if (res.data.success) {
                        resolve(res.data);
                    } else {
                        requestExpiredErr[requestName] = params;
                        reject(res.data);
                    }
                },
                fail: function (err) {
                    requestNetworkErr[requestName] = params
                    reject(err);
                },
                complete: function () {
                    delete requestRecord[requestName];
                }
            })
        })
    },

    /*
    * 终止请求
    * */
    abort: function (params) {
        let requestName = _getRequestName(params); //设置请求唯名称
        if (requestRecord[requestName]) {
            requestRecord[requestName].abort();
            delete requestRecord[requestName]
        };
    }
}

module.exports = Request